package com.netcracker.automonic.parser;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Parse data from table on <a
 * href="http://finviz.com/screener.ashx">Finviz.com</a>
 * 
 * @author lester
 * 
 */
public class StocksParser extends JsoupParser implements IParser {
	private static final Logger log = Logger.getLogger(StocksParser.class);
	private static final int START_COL_NUM = 2;
	private static final int MIDDLE_COL_NUM = 5;
	private static final int LAST_COL_NUM = 10;

	public StocksParser(String URL) {
		super.URL = URL;
	}

	public Map<String, List<String>> parseNonVaryData() {
		Map<String, List<String>> companiesAttr = parseDataFromTable(
				START_COL_NUM, MIDDLE_COL_NUM);
		return companiesAttr;
	}

	public Map<String, List<String>> parseVaryData() {
		Map<String, List<String>> companiesStats = parseDataFromTable(
				MIDDLE_COL_NUM + 1, LAST_COL_NUM);
		return companiesStats;
	}

	private Map<String, List<String>> parseDataFromTable(int startColumnIndex,
			int endColumnIndex) {
		doc = getDocumentByConnect();
		Map<String, List<String>> companiesInfo = new LinkedHashMap<String, List<String>>();
		while (doc != null) {
			Elements rows = doc.select("tr[class^=table-]");
			for (Element row : rows) {
				Elements values = row.getElementsByClass("body-table-nw");
				String companyTicker = values.get(1).text();
				List<String> companyInfo = new ArrayList<String>();
				for (int i = startColumnIndex; i <= endColumnIndex; i++) {
					companyInfo.add(values.get(i).text());
				}
				companiesInfo.put(companyTicker, companyInfo);
			}
			doc = getNextPage();
		}
		return companiesInfo;
	}

	@Override
	Document getNextPage() {
		String nextLink;
		Elements nextButton = doc.select("a[class=tab-link]:contains(next)");
		if (nextButton.first() != null) {
			nextLink = nextButton.first().attr("href");
			URL = "http://finviz.com/" + nextLink;
		} else
			return null;
		doc = getDocumentByConnect();
		return doc;
	}
}
